package cn.yangliu.jwt.web;

import cn.yangliu.jwt.comm.JsonResult;
import cn.yangliu.jwt.entity.User;
import cn.yangliu.jwt.service.UserService;
import cn.yangliu.jwt.tools.JwtTokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.spi.service.contexts.SecurityContext;

/**
 * @author 杨柳
 * @date 2019-05-22
 */
@RestController
@Api(value = "认证",tags = "认证")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    JwtTokenUtils jwtTokenUtils;

    @Value("${jwt.expiration}")
    private Long expiration;

    @PostMapping("/auth")
    @ApiOperation("认证")
    public JsonResult<String> auth(String username,String password){

        UserDetails userDetails = userService.loadUserByUsername(username);
        if (passwordEncoder.matches(password,userDetails.getPassword())){
            throw new BadCredentialsException("用户名或密码错误");
        }
        Authentication authenticate = new UsernamePasswordAuthenticationToken(userDetails,password);

        SecurityContextHolder.getContext().setAuthentication(authenticate);
        String jwtToken = jwtTokenUtils.generateToken(userDetails);
        jwtTokenUtils.setExpire(jwtToken,userDetails.getUsername(),expiration);
        return JsonResult.getInstance(jwtToken);
    }
}
